#!/usr/bin/env bash

if [[ $# -ne 1 ]]; then
    echo -e "Need 1 parameter, excute like this: ./init.sh projectname \033[1;31m[Error]\033[0m"
    exit 1
fi

# Check environment
which ack > /dev/null 2>&1
if [[ $? != 0 ]]; then
    echo -e "Please install ack \033[1;31m[Error]\033[0m"
    exit 1
else
    ACK=$(which ack)
fi
which perl > /dev/null 2>&1
if [[ $? != 0 ]]; then
    echo -e "Please install perl \033[1;31m[Error]\033[0m"
    exit 1
else
    PERL=$(which perl)
fi
which python > /dev/null 2>&1
if [[ $? != 0 ]]; then
    echo -e "Please install python \033[1;31m[Error]\033[0m"
    exit 1
else
    PYTHON=$(which python)
fi

# Clear useless files
ls -a | egrep -v "(bootstrap.py|buildout.cfg|init.sh|main|\.$|\.\.$)" | xargs rm -rf

# Rename project template
$ACK --ignore-file=is:init.sh --print0 -l "demo" | xargs -0 $PERL -p -i -e "s/demo/$1/g"
mv main/demo/ main/$1

# Buildout init
$PYTHON bootstrap.py

if [[ $? -ne 0 ]]; then
    echo -e "Initialize buildout failed \033[1;31m[Error]\033[0m"
    exit 1
fi

# Modify easy_install default mirror source to douban
find . -name "easy_install.py" | xargs sed -i  's#https://pypi.org/simple#http://pypi.douban.com/simple#g'

# Buildout
echo "All ready, please excute \"./bin/buildout\""
